package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.*;

public class BibliotecaApp {


    private final PrintStream printStream;
    private Library library;
    private UserInput userInput;
    private Menu menu;

    public BibliotecaApp(PrintStream printStream, Library library, UserInput userInput, Menu menu) {
        this.printStream = printStream;
        this.library = library;
        this.userInput = userInput;
        this.menu = menu;
    }

    public static void main(String[] args) {
        UserInput userInput = new UserInput(new BufferedReader(new InputStreamReader(System.in)));
        Map<String, String> bookList = new TreeMap<String, String>();

        bookList.put("To Kill A Mockingbird", "To Kill A Mockingbird");
        bookList.put("Anna Karenina", "Anna Karenina");
        bookList.put("Ender's Game", "Ender's Game");
        bookList.put("Brave New World", "Brave New World");
        Library library = new Library(bookList);
        Menu menu = new Menu();
        BibliotecaApp app = new BibliotecaApp(System.out, library, userInput, menu);
        app.start();
    }

    public void start() {
        printStream.println("Welcome to Biblioteca!\n");
        printBooksInLibrary();
        printMenu();

        boolean keepGoing = true;
        while (keepGoing) {
            String menuChoice = userInput.getInput();
            String menuChoiceInput = menu.parseUserInput(menuChoice);
            keepGoing = performMenuAction(menuChoiceInput);
        }
    }

    private boolean performMenuAction(String menuChoiceInput) {
        if (menuChoiceInput.equalsIgnoreCase("List books")) {
            printBooksInLibrary();
            return false;
        } else if (menuChoiceInput.equalsIgnoreCase("Checkout book")) {
            printBooksInLibrary();
            printStream.println("Select a book");

            String bookToCheckOut = userInput.getInput();
            library.checkOutBooks(bookToCheckOut);

            return false;
        } else if (menuChoiceInput.equalsIgnoreCase("Exit")) {
            return false;
        } else {
            printStream.println("Select a valid option!");
            return true;
        }
    }

    private void printBooksInLibrary() {
        printStream.println("These are the books in the library: ");
        printStream.println(library.listBooks());
    }

    public void printMenu() {
        printStream.println("Please select an option: ");
        printStream.println(menu.listMenuOptions());
    }


}
